const logger = require('log4js').getLogger()

module.exports = (req, res) => {
    require('../util/service').handlePost(req, res, (reqObj, resolve) => {
        if ((!reqObj.taobaoTradeParentId || !reqObj.auctionId) &&
            !reqObj.orderId &&
            (!reqObj.tradeParentId || !reqObj.itemId)) {
            resolve({
                result: -1,
                msg: '缺少参数'
            })
            return
        }
        new Promise(resolve => {
            require('../task/handleBillTask').findCustomerForBill({
                taobaoTradeParentId: reqObj.taobaoTradeParentId,
                auctionId: reqObj.auctionId,
                orderId: reqObj.orderId,
                tradeParentId: reqObj.tradeParentId,
                itemId: reqObj.itemId
            }).then(result => {
                resolve([result])
            }, result => {
                resolve(result || [])
            })
        }).then(result => {
            var promises = [Promise.resolve()]
            result.forEach(item => {
                promises.push(new Promise(resolve => {
                    const mongoMng = require('../mng/mongoMng')
                    if (!mongoMng.db) {
                        logger.error('[' + __filename + ':' + __line + ']', 'mongo not connect')
                        resolve('')
                        return
                    }
                    mongoMng.db.collection('log').find({
                        $or: [{
                            link: new RegExp('id=' + reqObj.auctionId),
                        }, {
                            link: new RegExp('http://a.m.tmall.com/i' + reqObj.auctionId + '.htm'),
                        }, {
                            link: new RegExp('https://a.m.taobao.com/i' + reqObj.auctionId + '.htm'),
                        }],
                        customer_phone: item
                    }).sort({
                        time: -1
                    }).limit(1).toArray((err, result) => {
                        if (err) {
                            logger.error('[' + __filename + ':' + __line + ']', err)
                            resolve('')
                            return
                        }
                        if (result.length == 0) {
                            resolve('')
                            return
                        }
                        resolve(result[0].time)
                    })
                }))
            })
            Promise.all(promises).then(_result => {
                resolve({
                    result: 1,
                    customer_phone: result,
                    log_time: _result.slice(1)
                })
            })
        })
    })
}